package com.hctforgreen.greenservice.net;

import android.content.Context;
import android.text.TextUtils;

import com.hctforgreen.greenservice.ctr.HctController;
import com.hctforgreen.greenservice.model.LoginResultEntity;
import com.hctforgreen.greenservice.utils.ContantsUtil;
import com.hctforgreen.greenservice.utils.HctConstants;
import com.hctforgreen.greenservice.utils.LogUtil;
import com.hctforgreen.greenservice.utils.LoginResultStoreUtil;
import com.hctforgreen.greenservice.utils.MachineCodeUtil;
import com.hctforgreen.greenservice.utils.MimeTypeUtil;
import com.hctforgreen.greenservice.utils.TokenUtil;
import com.mato.sdk.proxy.Proxy;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnRouteParams;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * Net通信底层操作
 *
 * @author Tallen Zhai
 */

public class NetAdapter {
    private static final String TAG = "NetAdapter";
    protected Context context;
    private String token;
    private String phone;
    private String IMEI;

    public NetAdapter(Context context) {
        this.context = context;

        initTokenAndPhone();
        initIMEI();
    }

    private void initTokenAndPhone() {
        LoginResultEntity loginResultEntity = LoginResultStoreUtil.get(context);
        this.token = loginResultEntity.token;
        this.phone = loginResultEntity.phone;
    }

    private void initIMEI() {
        MachineCodeUtil codeUtil = new MachineCodeUtil(context);
        this.IMEI = codeUtil.getIMEICode();
    }

    /**
     * 执行Post，访问正式服务器接口获取数据--------》
     * 获取开机密码、提交大机组信息、获取大机组开机密码审核状态、大机组报完成、获取开机密码的提醒及关联的资料、提交章节意见、提交书籍意见
     * 、追加反馈回复、提交反馈评分、 获取视频列表、获取类型下面的所有视频、根据关键字搜索视频
     *
     * @param netPath
     * @param actionName
     * @param params
     * @return
     * @throws Exception
     */
    public String invokeServerPost(String netPath, String actionName,
                                   List<NameValuePair> params) throws Exception {

        /**
         * 加密
         */
        if (!(HctController.APP_LOGIN_ACTION.equals(actionName) || HctController.GET_LOADING_INFO_ACTION
                .equals(actionName))) {

            netPath = "token-" + netPath;
            if (params == null) {

                params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("token", token));
                params.add(new BasicNameValuePair("phonet", phone));
                params.add(new BasicNameValuePair("imeiCodet", IMEI));

            } else {

                params.add(new BasicNameValuePair("token", token));
                params.add(new BasicNameValuePair("phonet", phone));
                params.add(new BasicNameValuePair("imeiCodet", IMEI));
            }

        }
        //拼接地址
        HttpPost post = new HttpPost(HctConstants.NET_URL + netPath
                + actionName);
        HttpEntity entity = new UrlEncodedFormEntity(params,
                HctConstants.NET_ENCODING);

        // 添加请求参数到请求对象
        post.setEntity(entity);
        DefaultHttpClient defaultHttpClient = new DefaultHttpClient();

        if (Proxy.getAddress() != null) {

            final HttpHost proxyHost = new HttpHost(Proxy.getAddress()
                    .getHost(), Proxy.getAddress().getPort());
            defaultHttpClient.getParams().setParameter(
                    ConnRouteParams.DEFAULT_PROXY, proxyHost);
        }
        defaultHttpClient.getParams().setParameter(
                CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);// 设置超时30秒
        defaultHttpClient.getParams().setParameter(
                CoreConnectionPNames.SO_TIMEOUT, 30000);// 读数据超时时间
        // 发送请求并等待响应
        HttpResponse response = defaultHttpClient.execute(post);
        int sCode = response.getStatusLine().getStatusCode();
        if (sCode == HttpStatus.SC_OK) {
            //Log.i("DATA", "执行submitBigUnitInfo（）----" + "正式2----"+sCode);
            //Log.i("DATA", "执行submitBigUnitInfo（）----" + "正式2----"+EntityUtils.toString(response.getEntity()));
            // 读响应数据
            return TokenUtil.checkToken(context,
                    EntityUtils.toString(response.getEntity()));

        } else
            //Log.i("DATA", "执行submitBigUnitInfo（）----" + "正式2----"+sCode);
            throw new Exception("http exception code:" + sCode);
    }

    /**
     * 关联提示接口用的HttpClient请求
     * 超时时间为10秒
     *
     * @param netPath
     * @param actionName
     * @param params
     * @return
     * @throws Exception
     */
    public String invokeServerPostForAssociation(String netPath, String actionName,
                                                 List<NameValuePair> params) throws Exception {

        /**
         * 加密
         */
        if (!(HctController.APP_LOGIN_ACTION.equals(actionName) || HctController.GET_LOADING_INFO_ACTION
                .equals(actionName))) {

            netPath = "token-" + netPath;
            if (params == null) {

                params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("token", token));
                params.add(new BasicNameValuePair("phonet", phone));
                params.add(new BasicNameValuePair("imeiCodet", IMEI));

            } else {

                params.add(new BasicNameValuePair("token", token));
                params.add(new BasicNameValuePair("phonet", phone));
                params.add(new BasicNameValuePair("imeiCodet", IMEI));
            }

        }
        //拼接地址
        HttpPost post = new HttpPost(HctConstants.NET_URL + netPath
                + actionName);
        HttpEntity entity = new UrlEncodedFormEntity(params,
                HctConstants.NET_ENCODING);

        // 添加请求参数到请求对象
        post.setEntity(entity);
        DefaultHttpClient defaultHttpClient = new DefaultHttpClient();

        if (Proxy.getAddress() != null) {

            final HttpHost proxyHost = new HttpHost(Proxy.getAddress()
                    .getHost(), Proxy.getAddress().getPort());
            defaultHttpClient.getParams().setParameter(
                    ConnRouteParams.DEFAULT_PROXY, proxyHost);
        }
        defaultHttpClient.getParams().setParameter(
                CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);// 设置超时30秒
        defaultHttpClient.getParams().setParameter(
                CoreConnectionPNames.SO_TIMEOUT, 10000);// 读数据超时时间
        // 发送请求并等待响应
        HttpResponse response = defaultHttpClient.execute(post);
        int sCode = response.getStatusLine().getStatusCode();
        if (sCode == HttpStatus.SC_OK) {
            //Log.i("DATA", "执行submitBigUnitInfo（）----" + "正式2----"+sCode);
            //Log.i("DATA", "执行submitBigUnitInfo（）----" + "正式2----"+EntityUtils.toString(response.getEntity()));
            // 读响应数据
            return TokenUtil.checkToken(context,
                    EntityUtils.toString(response.getEntity()));

        } else
            //Log.i("DATA", "执行submitBigUnitInfo（）----" + "正式2----"+sCode);
            throw new Exception("http exception code:" + sCode);
    }

    /**
     * 执行post-------云服务器
     *
     * @param netPath
     * @param actionName
     * @param params
     * @return
     * @throws Exception
     */
    public String invokeServerPostForClound(String netPath, String actionName,
                                            List<NameValuePair> params) throws Exception {

        /**
         * 加密
         */
        if (!(HctController.APP_LOGIN_ACTION.equals(actionName) || HctController.GET_LOADING_INFO_ACTION
                .equals(actionName))) {

            netPath = "token-" + netPath;
            if (params == null) {

                params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("token", token));
                params.add(new BasicNameValuePair("phonet", phone));
                params.add(new BasicNameValuePair("imeiCodet", IMEI));

            } else {

                params.add(new BasicNameValuePair("token", token));
                params.add(new BasicNameValuePair("phonet", phone));
                params.add(new BasicNameValuePair("imeiCodet", IMEI));
            }

        }
        //拼接地址
        HttpPost post = new HttpPost(HctConstants.NET_URL_DISASTER + netPath
                + actionName);
        HttpEntity entity = new UrlEncodedFormEntity(params,
                HctConstants.NET_ENCODING);

        // 添加请求参数到请求对象
        post.setEntity(entity);
        DefaultHttpClient defaultHttpClient = new DefaultHttpClient();

        if (Proxy.getAddress() != null) {

            final HttpHost proxyHost = new HttpHost(Proxy.getAddress()
                    .getHost(), Proxy.getAddress().getPort());
            defaultHttpClient.getParams().setParameter(
                    ConnRouteParams.DEFAULT_PROXY, proxyHost);
        }
        defaultHttpClient.getParams().setParameter(
                CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);// 设置超时30秒
        defaultHttpClient.getParams().setParameter(
                CoreConnectionPNames.SO_TIMEOUT, 30000);// 读数据超时时间
        // 发送请求并等待响应
        HttpResponse response = defaultHttpClient.execute(post);
        int sCode = response.getStatusLine().getStatusCode();
        if (sCode == HttpStatus.SC_OK) {
            // 读响应数据
            // Log.i("DATA", "invokeServerPost----7");
            // Log.i("DATA",
            // "invokeServerPost----8"
            // + EntityUtils.toString(response.getEntity()));
            return TokenUtil.checkToken(context,
                    EntityUtils.toString(response.getEntity()));

        } else
            throw new Exception("http exception code:" + sCode);
    }

    /**
     * 执行Get--- 登录、获取备用密码
     *
     * @param netPath
     * @param actionName
     * @param params
     * @return
     * @throws Exception
     */
    public String invokeServerGet(String netPath, String actionName,
                                  List<NameValuePair> params) throws Exception {
        /**
         * 接口加密
         */
        if (!(HctController.APP_LOGIN_ACTION.equals(actionName) || HctController.GET_LOADING_INFO_ACTION
                .equals(actionName))) {
            netPath = "token-" + netPath;
            if (params == null) {
                params = new ArrayList<>();
                params.add(new BasicNameValuePair("token", token));
                params.add(new BasicNameValuePair("phonet", phone));
                params.add(new BasicNameValuePair("imeiCodet", IMEI));
            } else {
                params.add(new BasicNameValuePair("token", token));
                params.add(new BasicNameValuePair("phonet", phone));
                params.add(new BasicNameValuePair("imeiCodet", IMEI));
            }
            if (ContantsUtil.isSubmitPaper) {//是否是提交试卷，如果是提交试卷则把角色提交上去
                ContantsUtil.isSubmitPaper = false;
                params.add(new BasicNameValuePair("staffRole", ContantsUtil.sRolePosition));
            }
        }

        String url = HctConstants.NET_URL + netPath + actionName + "?" + buildQueryString(params);
        LogUtil.d(TAG, "url = " + url);
        HttpGet get = new HttpGet(url);
        DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
        if (Proxy.getAddress() != null) {
            final HttpHost proxyHost = new HttpHost(Proxy.getAddress().getHost(), Proxy.getAddress().getPort());
            defaultHttpClient.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxyHost);
        }
        defaultHttpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);// 设置超时30秒
        defaultHttpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);// 读数据超时时间
        HttpResponse response = defaultHttpClient.execute(get);
        int sCode = response.getStatusLine().getStatusCode();
        LogUtil.d(TAG, "sCode = " + sCode);
        if (sCode == HttpStatus.SC_OK) {
            return TokenUtil.checkToken(context, EntityUtils.toString(response.getEntity()));
        } else
            throw new Exception("http exception code:" + sCode);
    }

    /**
     * 执行Get
     *
     * @param netPath
     * @param actionName
     * @param params
     * @return
     * @throws Exception
     */
    public String invokeServerGetForCloud(String netPath, String actionName, List<NameValuePair> params) throws Exception {

        //接口加密
        if (!(HctController.APP_LOGIN_ACTION.equals(actionName) || HctController.GET_LOADING_INFO_ACTION
                .equals(actionName))) {
            netPath = "token-" + netPath;
            if (params == null) {
                params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("token", token));
                params.add(new BasicNameValuePair("phonet", phone));
                params.add(new BasicNameValuePair("imeiCodet", IMEI));
            } else {
                params.add(new BasicNameValuePair("token", token));
                params.add(new BasicNameValuePair("phonet", phone));
                params.add(new BasicNameValuePair("imeiCodet", IMEI));
            }
        }
        String url = HctConstants.NET_URL_DISASTER + netPath + actionName + "?"
                + buildQueryString(params);
        HttpGet get = new HttpGet(url);
        DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
        if (Proxy.getAddress() != null) {
            final HttpHost proxyHost = new HttpHost(Proxy.getAddress()
                    .getHost(), Proxy.getAddress().getPort());
            defaultHttpClient.getParams().setParameter(
                    ConnRouteParams.DEFAULT_PROXY, proxyHost);
        }
        defaultHttpClient.getParams().setParameter(
                CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);// 设置超时30秒
        defaultHttpClient.getParams().setParameter(
                CoreConnectionPNames.SO_TIMEOUT, 30000);// 读数据超时时间
        HttpResponse response = defaultHttpClient.execute(get);
        int sCode = response.getStatusLine().getStatusCode();
        if (sCode == HttpStatus.SC_OK) {
            //Log.i("DATA", "登录灾备---"+sCode);
            return TokenUtil.checkToken(context,
                    EntityUtils.toString(response.getEntity()));
        } else
            //Log.i("DATA", "登录灾备---"+sCode);
            throw new Exception("http exception code:" + sCode);
    }

    private String buildQueryString(List<NameValuePair> params) {
        String getData = "";
        int size = params.size();
        for (int i = 0; i < size; i++) {
            NameValuePair nameValuePair = params.get(i);
            try {
                if (nameValuePair.getName() == null) {
                    getData += nameValuePair.getName() + "=&";
                } else {
                    getData += nameValuePair.getName() + "="
                            + URLEncoder.encode(nameValuePair.getValue(), /* "GB2312" */
                            "UTF-8") + "&";
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        if (getData.length() > 1)
            getData = getData.substring(0, getData.length() - 1);

        return getData;
    }

    public String invokeServerPostPhoto(String netPath, String actionName,
                                        List<NameValuePair> params, List<String> filepaths,
                                        List<String> videoPathes, String attachment) throws Exception {
        //加密数据
        if (!(HctController.APP_LOGIN_ACTION.equals(actionName) || HctController.GET_LOADING_INFO_ACTION
                .equals(actionName))) {
            netPath = "token-" + netPath;
            if (params == null) {
                params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("token", token));
                params.add(new BasicNameValuePair("phonet", phone));
                params.add(new BasicNameValuePair("imeiCodet", IMEI));
            } else {
                params.add(new BasicNameValuePair("token", token));
                params.add(new BasicNameValuePair("phonet", phone));
                params.add(new BasicNameValuePair("imeiCodet", IMEI));
            }
        }

        HttpPost httppost = new HttpPost(HctConstants.NET_URL + netPath
                + actionName);
        httppost.addHeader("charset", HTTP.UTF_8);

        HttpClient httpclient = new DefaultHttpClient();
        if (Proxy.getAddress() != null) {
            final HttpHost proxyHost = new HttpHost(Proxy.getAddress()
                    .getHost(), Proxy.getAddress().getPort());
            httpclient.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY,
                    proxyHost);
        }
        httpclient.getParams().setParameter(
                CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        httpclient.getParams().setParameter("charset", HTTP.UTF_8);

        MultipartEntity mpEntity = new MultipartEntity();
        for (int i = 0; i < filepaths.size(); i++) {
            String path = filepaths.get(i);
            // 传文件和类型
            File file = new File(path);
            ContentBody cbFile = new FileBody(file,
                    MimeTypeUtil.getMimeTypeByFileName(file.getName()));

            mpEntity.addPart("pic_file" + String.valueOf(i + 1), cbFile);
        }
        for (int i = 0; i < videoPathes.size(); i++) {
            String path = videoPathes.get(i);
            // 传文件和类型
            File file = new File(path);
            ContentBody cbFile = new FileBody(file,
                    MimeTypeUtil.getMimeTypeByFileName(file.getName()));
            mpEntity.addPart("video", cbFile);
        }
        if (!TextUtils.isEmpty(attachment)) {
            File upFile = new File(attachment);
            if (upFile.exists()) {
                ContentBody cbFile = new FileBody(upFile);
                mpEntity.addPart("attachment", cbFile);
                params.add(new BasicNameValuePair("attFileName", upFile
                        .getName()));
            }
        }

        for (int i = 0; i < params.size(); i++) {
            mpEntity.addPart(
                    params.get(i).getName(),
                    new StringBody(params.get(i).getValue(), Charset
                            .forName(HctConstants.NET_ENCODING)));
        }
        // 设置参数
        httppost.setEntity(mpEntity);
        HttpResponse response = null;
        // 执行上传
        response = httpclient.execute(httppost);

        int sCode = response.getStatusLine().getStatusCode();
        if (sCode == HttpStatus.SC_OK) {
            return TokenUtil.checkToken(context,
                    EntityUtils.toString(response.getEntity()));
        } else
            throw new Exception("http exception code:" + sCode);

    }

    /**
     * 执行Get
     *
     * @param netPath
     * @return
     * @throws Exception
     */
    public String invokeServerGet(String netPath) throws Exception {
        String url = netPath;
        HttpGet get = new HttpGet(url);
        DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
        if (Proxy.getAddress() != null) {
            final HttpHost proxyHost = new HttpHost(Proxy.getAddress()
                    .getHost(), Proxy.getAddress().getPort());
            defaultHttpClient.getParams().setParameter(
                    ConnRouteParams.DEFAULT_PROXY, proxyHost);
        }
        defaultHttpClient.getParams().setParameter(
                CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);// 设置超时30秒
        defaultHttpClient.getParams().setParameter(
                CoreConnectionPNames.SO_TIMEOUT, 30000);// 读数据超时时间
        HttpResponse response = defaultHttpClient.execute(get);
        int sCode = response.getStatusLine().getStatusCode();
        if (sCode == HttpStatus.SC_OK) {
            return EntityUtils.toString(response.getEntity());
        } else
            throw new Exception("http exception code:" + sCode);
    }

}
